﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using CTThrottling.Common;
using StackExchange.Redis;

namespace ThrottlingWebTest
{
    public class MvcApplication : System.Web.HttpApplication
    {
        //#region

        //private readonly RedisStackExchangeHelper _redis = new RedisStackExchangeHelper();
        //private IDatabase _db = null;
        //#endregion

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

        protected void Application_End(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //_db = _redis.GetDatabase();
            //var clientIp = WebHelper.GetClientIp();

            ////if (!db.LockTake("test", token, TimeSpan.FromSeconds(60)))
            ////{
            ////    Context.RewritePath("~/StaticHtml/test.html");
            ////}

            //#region Ip单位时间访问次数限制

            ////var aa = Context.Request.Url.AbsoluteUri;
            //var times = _db.StringIncrement(clientIp);
            //if (1 == times)
            //{
            //    _db.KeyExpire(clientIp, TimeSpan.FromSeconds(60));
            //}
            //if (times > 3)
            //{
            //    Context.RewritePath("~/StaticHtml/test.html");
            //    var liveTime = _db.KeyTimeToLive(clientIp);
            //    if (liveTime == null)
            //    {
            //        _db.KeyExpire(clientIp, TimeSpan.FromSeconds(60));
            //    }
            //}

            //#endregion

        }

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            //db.LockRelease("test", token);
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

    }
}
